<template>
	<view id="count_down">
		<view class="time_box">{{day}}</view>
		<view class="time_txt">天</view>
		<view class="time_box">{{hour}}</view>
		<view class="time_txt">时</view>
		<view class="time_box">{{min}}</view>
		<view class="time_txt">分</view>
		<view class="time_box">{{second}}</view>
		<view class="time_txt">秒</view>
	</view>
</template>

<script>
	export default {
		name: "count-down",
		data() {
			return {
				// curStartTime: '2022-12-25 08:00:00',
				day: '0',
				hour: '00',
				min: '00',
				second: '00',
			};
		},
		props: { //接收父组件的数据
			starTime: {
				type: String,
				default: ''
			},
		},
		mounted() {
			this.countTime(this.starTime)
		},
		methods: {
			countTime() {
				// 获取当前时间
				let date = new Date()
				let now = date.getTime()
				// 设置截止时间
				let endDate = new Date(this.starTime) // this.starTime需要倒计时的日期
				let end = endDate.getTime()
				// 时间差
				let leftTime = end - now
				// 定义变量 d,h,m,s保存倒计时的时间
				if (leftTime >= 0) {
					// 天
					this.day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
					// 时
					let h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
					this.hour = h < 10 ? '0' + h : h
					// 分
					let m = Math.floor(leftTime / 1000 / 60 % 60)
					this.min = m < 10 ? '0' + m : m
					// 秒
					let s = Math.floor(leftTime / 1000 % 60)
					this.second = s < 10 ? '0' + s : s
				} else {
					this.day = 0
					this.hour = '00'
					this.min = '00'
					this.second = '00'
				}
				// 等于0的时候不调用
				if (Number(this.hour) === 0 && Number(this.day) === 0 && Number(this.min) === 0 && Number(this.second) ===
					0) {
					this.$emit('endSuccess')
					return
				} else {
					// 递归每秒调用countTime方法，显示动态时间效果,
					setTimeout(this.countTime, 1000)
				}
			},
		},
	}
</script>

<style>
	#count_down {
		display: flex;
		align-items: center;
	}

	.time_box {
		width: 38rpx;
		height: 38rpx;
		border-radius: 6rpx;
		background: #A67517;
		color: #FFFFFF;
		font-size: 24rpx;
		text-align: center;
		line-height: 38rpx;
		margin-right: 10rpx;
	}

	.time_txt {
		font-size: 24rpx;
		color: #A67517;
		margin-right: 10rpx;
	}
</style>
